package com.ruoyi.candidate.controller;

import com.ruoyi.candidate.domain.Candidate;

import com.ruoyi.candidate.service.ICandidateService;
import com.ruoyi.examApproval.domain.Approval;
import com.ruoyi.examApproval.service.impl.ApprovalService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.order.domain.Order;

import com.ruoyi.order.service.impl.OrderServiceImpl;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "考生管理-基础功能")
@RestController
@RequestMapping("/candidate")
public class CandidateController extends BaseController{

    @Autowired
    private ICandidateService candidateService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private ISysUserService userService;

    /**
     * 注册新的考生
     * @param candidate 考生信息
     * @return 注册结果
     */
    @ApiOperation("考生管理-基础功能 - 考生注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody Candidate candidate) {
        // 在系统中注册用户，角色为考生
        SysUser user = new SysUser();
        user.setPassword(candidate.getPassword());
        user.setPhonenumber(candidate.getPhone());
        user.setUserName(candidate.getId_number());
        user.setNickName(candidate.getName());
        user.setStatus("0");  // 0 表示正常状态
        user.setCreateBy("ruoyi");
        // 密码加密
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
//        user.setPassword(candidate.getPassword());

        // 检查用户名和手机号码是否唯一
        if (!userService.checkUserNameUnique(user)) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (!userService.checkPhoneUnique(user)) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }

        // 插入系统用户
        userService.insertUser(user);
        // 调用接口查询新插入的系统用户id
        Long user_id = userService.selectUserByUserName(user.getUserName()).getUserId();
        user.setRoleId(100L);  // 100 为考生角色编码
        // 设置用户和角色的对应关系
        userService.insertUserAuth(user_id, new Long[]{100L});
        // 返回注册对象
        return toAjax(candidateService.register(candidate));
    }

    /**
     * 考生登录
     * @param idNumber 身份证号
     * @param password 密码
     * @return 考生信息
     */
                @ApiOperation("考生管理 - 考生登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestParam String idNumber,@RequestParam String password) {

        try {
            String token = loginService.login(idNumber, password, "", "");
            AjaxResult ajax = AjaxResult.success(candidateService.login(idNumber, password));
            ajax.put("token", token);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.toString());
        }
    }


    /**
     * 修改考生密码
     * @param idNumber 身份证号
     * @param phone 电话号码
     * @param newPassword 新密码
     * @return 修改结果
     */
                @ApiOperation("考生管理 - 修改密码")
    @PostMapping("/modifyPassword")
    public AjaxResult modifyPassword(@RequestParam String idNumber, @RequestParam String phone, @RequestParam String newPassword) {
        // 修改 Candidate 密码
        int result = candidateService.modifyPassword(idNumber, phone, newPassword);
        if (result > 0) {
            // 查询对应的系统用户
            SysUser user = userService.selectUserByUserName(idNumber);
            if (user != null) {
                // 修改系统用户的密码
                userService.resetUserPwd(user.getUserName(),SecurityUtils.encryptPassword(newPassword));
            }
        }
        return toAjax(result);
    }

    /**
     * 更新考生的报名相关信息
     * @param candidate 考生信息
     * @return 更新结果
     */
                @ApiOperation("考生管理 - 更新报名信息")
    @PostMapping("/updateRegistrationInfo")
    public AjaxResult updateRegistrationInfo(@RequestBody Candidate candidate) {
        try{
            AjaxResult ajax = AjaxResult.success(candidateService.updateRegistrationInfo(candidate));
            // 将考生报名相关信息和审核表相关联
            // 添加考生报名信息时同步更新审核表
            // 检查是否有数据，如果无数据，则添加数据，有数据则不进行更改
            ApprovalService approvalService = new ApprovalService();
            Approval existApproval = approvalService.selectApprovalByCandidateId(candidate.getId_number());
            if(existApproval != null){
                Approval approval = new Approval();
                approval.setCandidateId(candidate.getId_number());
                approvalService.insertApproval(approval);
            }
            // 添加考生报名信息的订单信息
            OrderServiceImpl orderService = new OrderServiceImpl();
            Order existOrder = orderService.selectOrderById(candidate.getId_number());
            if(existOrder != null){
                Order order = new Order();
                order.setCandidate_id(candidate.getId_number());
                order.setPayment_status("未缴费");
                orderService.insertOrder(order);
            }
            return ajax;
        }catch(Exception e){
            return AjaxResult.error(e.toString());
        }
    }

    /**
     * 更新考生的基本信息
     * @param candidate 考生信息
     * @return 更新结果
     */
                @ApiOperation("考生管理 - 更新基本信息")
    @PostMapping("/updateBasicInfo")
    public AjaxResult updateBasicInfo(@RequestBody Candidate candidate) {
        // 更新 Candidate 基本信息
        int result = candidateService.updateBasicInfo(candidate);
        if (result > 0) {
            // 查询对应的系统用户
            SysUser user = userService.selectUserByUserName(candidate.getId_number());
            if (user != null) {
                // 更新系统用户的基本信息
                user.setPhonenumber(candidate.getPhone());
                user.setNickName(candidate.getName());
                user.setSex(candidate.getGender());  // 假设 gender 与系统用户性别字段一致
                userService.updateUserProfile(user);
            }
        }
        return toAjax(result);
    }

    /**
     * 更新或添加考生的收取通知书信息
     * @param candidate 考生信息
     * @return 更新结果
     */
                @ApiOperation("考生管理 - 更新通知书信息")
    @PostMapping("/updateNotificationInfo")
    public AjaxResult updateNotificationInfo(@RequestBody Candidate candidate) {
        return toAjax(candidateService.updateNotificationInfo(candidate));
    }

    /**
     * 根据考生编号删除考生信息
     * @param id 考生编号
     * @return 删除结果
     */
                @ApiOperation("考生管理 - 根据ID删除考生")
    @DeleteMapping("/delete")
    public AjaxResult deleteCandidateById(@RequestParam Long id) {
        // 查询考生信息
        Candidate candidate = candidateService.getCandidateById(id);
        if (candidate == null) {
            return AjaxResult.error("考生信息不存在");
        }
        // 删除系统用户信息
        SysUser user = userService.selectUserByUserName(candidate.getId_number());
        if (user != null) {
            userService.deleteUserById(user.getUserId());
        }
        // 删除考生信息
        return toAjax(candidateService.deleteCandidateById(id));
    }

    /**
     * 根据身份证号查询考生信息
     * @param idNumber 身份证号
     * @return 考生信息
     */
                @ApiOperation("考生管理 - 根据身份证号查询考生")
    @GetMapping("/getByIdNumber")
    public AjaxResult getCandidateByIdNumber(@RequestParam String idNumber) {
        return success(candidateService.getCandidateByIdNumber(idNumber));
    }

                @ApiOperation("考生管理 - 根据ID获取基本信息")
    @GetMapping("/getBaseInfoById")
    public AjaxResult getBaseInfoById(@RequestParam Long id){
        return success(candidateService.getBaseInfoById(id));
    }

    /**
     * 根据考生编号查询考生信息
     * @param id 考生编号
     * @return 考生信息
     */
                @ApiOperation("考生管理 - 根据ID查询考生")
    @GetMapping("/getById")
    public AjaxResult getCandidateById(@RequestParam Long id) {
        return success(candidateService.getCandidateById(id));
    }
}
